<template>
	<view class="pb-safe-area">
		<view class="p-4 flex flex-column grid-gap-4" v-if="list.length > 0 || loading">
			<x-coupon-item v-for="(item, index) in list" :key="index" :item="item">
				<template #action>
					<template v-if="item.is_receive === 2">
						<button class="btn-success btn-round shadow text-nowrap" size="mini"
							@tap="$page.switch('/pages/index/index')">去使用</button>
					</template>
					<template v-else-if="item.is_receive === 1">
						<button class="btn-placeholder btn-round shadow text-nowrap" size="mini">{{ item.receive_tips
							}}</button>
					</template>
					<template v-else-if="item.num <= 0">
						<button class="btn-placeholder btn-round shadow text-nowrap" size="mini">已领完</button>
					</template>
					<template v-else-if="item.is_receive === 0">
						<button class="btn-primary btn-round shadow text-nowrap" @click="receive(item)"
							size="mini">立即领取</button>
					</template>
				</template>
			</x-coupon-item>
		</view>
		<x-empty type="order" v-else text="暂无优惠券"></x-empty>
		<x-loading v-if="loading" />
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { $api, $message, $page } from '@/utils';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from "@/stores";
const UserStore = useUserStore();
const loading = ref(false);
const list = ref([]);
const getList = () => {
	loading.value = true;
	$api.Coupon.receiveList().then((data: any) => {
		list.value = data;
	}).catch(() => { }).finally(() => {
		loading.value = false;
	})
}
const receive = (item: any) => {
	if (UserStore.hasLogin()) {
		loading.value = true;
		$api.Coupon.receive(item.id).then(() => {
			$message.success('领取成功');
			getList();
		}).catch((err: any) => {
			$message.error(err.msg);
		}).finally(() => {
			loading.value = false;
		})
	} else {
		$page.re('/pages/login/login')
	}
}
onLoad(() => {
	getList();
})
</script>

<style lang="scss" scoped>
</style>
